package com.qyhl.webtv.module_news.news.jlnews.list;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsStyleBean;
import com.qyhl.webtv.commonlib.item.ItemActivity;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCirclePicture;
import com.qyhl.webtv.commonlib.item.ItemCircleText;
import com.qyhl.webtv.commonlib.item.ItemCircleTopic;
import com.qyhl.webtv.commonlib.item.ItemCircleVideo;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemOtherAdv;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemScoop;
import com.qyhl.webtv.commonlib.item.ItemScoopTopic;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTeleText;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class JLNewsListFragment extends BaseFragment implements JLNewsListContract.JLNewsListView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private View view;

    private JLNewsListPresenter mPresenter;

    private boolean hasPicture;//是否是无图


    private List<GlobalNewsBean> indexList;

    private int position;

    private int[] pos;//改变样式的位置


    private int type;

    private int page = 1;

    private List<GlobalNewsBean> mDataList = new ArrayList<>();

    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;



    public void setType(int type) {
        this.type = type;
    }

    public static JLNewsListFragment newInstance(int type) {
        JLNewsListFragment fragment = new JLNewsListFragment();
        fragment.setType(type);
        return fragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();
        setListeners();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
        }
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.news_fragment_jlnews_list, null);
    }

    @Override
    protected void create() {
        mPresenter = new JLNewsListPresenter(this);
    }

    @Override
    protected void setListener() {
        loadData();
    }

    @Override
    protected void onFirstVisible() {
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        recycleView.addItemDecoration(new com.luck.picture.lib.decoration.RecycleViewDivider(
                getContext(), LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(getContext(), R.color.global_gray_lv3)));
        mAdapter = new MultiItemTypeAdapter<>(getContext(), mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(getContext()));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(getContext()));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemCatchNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonRight(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(getContext()));
        mAdapter.addItemViewDelegate(new ItemGoodLife(getContext()));
        mAdapter.addItemViewDelegate(new ItemNoPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemTitleNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemTopNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoRight(getContext()));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(getContext()));
        mAdapter.addItemViewDelegate(new ItemUnion(getContext()));
        mAdapter.addItemViewDelegate(new ItemTeleText(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(getContext()));
        mAdapter.addItemViewDelegate(new ItemCircleVideo(getContext()));
        mAdapter.addItemViewDelegate(new ItemCirclePicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemCircleText());
        mAdapter.addItemViewDelegate(new ItemCircleTopic(getContext()));
        mAdapter.addItemViewDelegate(new ItemScoop());
        mAdapter.addItemViewDelegate(new ItemScoopTopic());
        mAdapter.addItemViewDelegate(new ItemActivity(getContext()));
        mAdapter.addItemViewDelegate(new ItemOtherAdv(getActivity()));
        recycleView.setAdapter(mAdapter);

        mPresenter.getList(type, page + "");
    }

    private void setListeners() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            page = 1;
            mPresenter.getList(type, page + "");
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getList(type, page + "");
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                mPresenter.getList(type, page + "");
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mDataList.get(position).getNewsId());
                RouterManager.router(ARouterPathConstant.JL_NEWS,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setListData(List<NewsBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        setNews(beanList);
        if (isMore) {
            refreshLayout.finishLoadMore();
            mDataList.addAll(indexList);
        } else {
            mDataList.clear();
            mDataList.addAll(indexList);
            refreshLayout.finishRefresh();
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(int code, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            page--;
            refreshLayout.finishLoadMore();
            if (code == 1) {
                showToast("获取失败，请稍后再试！", 4);
            }
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText("暂无内容或获取列表失败！");
        }
    }

    private void setNews(List<NewsBean> beanList) {
        indexList = new ArrayList<>();
        boolean globalStyle;
        int globalCommon;
        int globalVideo;
        try {
            globalStyle = CommonUtils.getInstance().getGlobalStyle();
            globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
            globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
        } catch (Exception e) {
            globalStyle = false;
            globalCommon = 0;
            globalVideo = 0;
        }

        //改变样式
        for (int i = 0; i < beanList.size(); i++) {
            if (isSpecial(i)) {
                if (globalStyle) {
                    position++;
                }
                List<NewsStyleBean> styleBeanList = CommonUtils.getInstance().getGlobalStyleBeanList();
                beanList.get(i).setCommonStyle(styleBeanList.get(position).getCommonStyle());
                beanList.get(i).setVideoStyle(styleBeanList.get(position).getVideoStyle());
            } else {
                beanList.get(i).setCommonStyle(globalCommon);
                beanList.get(i).setVideoStyle(globalVideo);
            }
        }

        //数据类型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "";
            int style = 0;
            switch (bean.getType()) {
                case "JLVideoNews":
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "JLCommonNews":
                    type = "1";
                    style = bean.getCommonStyle();
                    break;
                case "JLOutNews":
                    type = "8";
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getLogo(), style, type, Integer.parseInt(bean.getHitCount()), bean.getSource(), hasPicture, bean.getCommentCount()));
        }

    }

    /**
     * 判断当前位置是否是特殊位置
     */
    private boolean isSpecial(int index) {
        position = 0;
        try {
            for (int i = 0; i < pos.length; i++) {
                if (pos[i] == (index + 1)) {
                    position = i;
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
}
